package com.xuyuan.util;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.OrderComparator;
import org.springframework.core.env.Environment;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class SpringUtil implements ApplicationContextInitializer {
    private static ApplicationContext applicationContext = null;

    public SpringUtil() {
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public static String getApplicationNameNoVersion() {
        return getEnvironment().getProperty("spring.application.name");
    }

    public static Environment getEnvironment() {
        return getApplicationContext().getEnvironment();
    }

    public static Map<String, ?> getBeanOfType(Class<?> clazz) {
        return getApplicationContext().getBeansOfType(clazz);
    }

    public static <T> List<T> getBeansListOfTypeWithOrder(Class<T> clazz) {
        Map<String, T> beansOfType = getApplicationContext().getBeansOfType(clazz, true, true);
        return (List) beansOfType.values().stream().sorted(new OrderComparator()).collect(Collectors.toList());
    }

    public static <T> T getBean(Class<T> clazz) {
        return getApplicationContext().getBean(clazz);
    }

    public static Object getBeanByPath(Class<?> clazz) {
        return getApplicationContext().getBean(clazz.getName());
    }

    public static Object getBean(String beanId) {
        return getApplicationContext().getBean(beanId);
    }

    public void initialize(ConfigurableApplicationContext applicationContext) {
        SpringUtil.applicationContext = applicationContext;
    }
}
